﻿using UnityEngine;
using System.Collections;


public class MonoSingleton<T> : MonoBehaviour where T : MonoSingleton<T>
{
    private static T _instance;

    public static T instance
    {
        get
        {
            CreateInstance();
            return _instance;
        }
    }

    public static void CreateInstance(bool bDontDestroy = false)
    {
        if (_instance == null)
        {
            GameObject go = new GameObject(typeof(T).Name);
            _instance = go.AddComponent<T>();
            //(_instance as MonoSingleton<T>).SetCapacity();
            //sunwenhao: init will be call in awake func,this will be call twice
            //_instance.Init();
            if (bDontDestroy)
            {
                DontDestroyOnLoad(go);
            }
        }
    }

    public static void DestroyInstance()
    {
        if (_instance != null)
        {
            Destroy(_instance);
        }
    }

    public static bool HasInstance()
    {
        return _instance != null;
    }

    void Awake()
    {
        if (_instance == null)
        {
            _instance = this as T;
            //(_instance as MonoSingleton<T>).SetCapacity();
            _instance.Init();
            DontDestroyOnLoad(gameObject);
        }
#if DEBUG_LOGOUT
        else
        {
            DebugHelper.LogError("Error: " + typeof (T).Name + " Has More than One Instance!!!!");
        }
#endif
    }

    void OnDestroy()
    {
        if (_instance != null)
        {
            UnInit();
            Destroy(gameObject);
            _instance = null;
        }
    }

    protected virtual void Init()
    {

    }

    protected virtual void UnInit()
    {

    }
}
